package com.yugu.park.aspectj;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import com.yugu.park.annotation.SensitiveField;
import com.yugu.park.filter.SensitiveFilter;

import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Field;
import java.util.Objects;

import javax.annotation.Resource;
/**
 * 敏感词切面
 *
 * @author: guxf
 * @date:2023-08-02
 */
@Slf4j
@Aspect
@Component
public class SensitiveAspect {
	@Resource
    private SensitiveFilter filter;
	@Pointcut("@annotation(com.yugu.park.annotation.SensitiveMethod)")
    public void annotationPointCut() {
    }
    
    @Before("annotationPointCut()")
    public void  before(JoinPoint joinPoint) {
        try {
            Object requestObj = joinPoint.getArgs()[0];
            handleEncrypt(requestObj);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            log.error("SecureFieldAop处理出现异常{}", throwable);
        }
    }

    /**
     * 敏感词处理
     *
     * @param requestObj
     */
    private void handleEncrypt(Object requestObj) throws IllegalAccessException {
        if (Objects.isNull(requestObj)) {
            return;
        }
        Field[] fields = requestObj.getClass().getDeclaredFields();
        for (Field field : fields) {
            boolean hasSecureField = field.isAnnotationPresent(SensitiveField.class);
            if (hasSecureField) {
                field.setAccessible(true);
                String plaintextValue = (String) field.get(requestObj);
                String encryptValue = filter.filter(plaintextValue);
                field.set(requestObj, encryptValue);
            }
        }
    }

}
